import tkinter as tk
from tkinter import messagebox
from tkinter import  filedialog, Entry, Button, StringVar
import math
from PIL import Image, ImageTk
import os
import plistlib
import GetPList

def create_window(parent=None):

    # 创建窗口
    if parent is None:
        root = tk.Tk()
    else:
        root = tk.Toplevel(parent)
    root.title("plist批量切割")
    root.config(bg="grey")
    root.geometry("1000x1000+0+0")

    global offX, offY
    offX = 60
    offY = 50

    global imgs_scale, scale_value, scale_index, imgs_Dic, dirName_Dic, cur_directory_type_index
    scale_value = 1
    imgs_scale = []
    scale_index = 0
    imgs_Dic = {}
    dirName_Dic = {}
    cur_directory_type_index = 0

    check_var = tk.IntVar()

    # 第一行：按钮+输入框
    entry_scale_frame_path = StringVar()
    entry_path1 = Entry(root, textvariable=entry_scale_frame_path)
    entry_path1.place(x=offX + 350, y=offY - 34)

    button1 = Button(root, text="输入目录", command=lambda: select_directory(entry_scale_frame_path),
                     bg='skyblue')
    button1.place(x=offX + 500, y=offY - 37)

    # 第二行：输入框+输入框
    entry_scale_out_path = StringVar()
    entry_path2 = Entry(root, textvariable=entry_scale_out_path)
    entry_path2.place(x=offX + 350, y=offY + 3)
    button2 = Button(root, text="输出目录", command=lambda: select_out_directory(entry_scale_out_path),
                     bg='skyblue')
    button2.place(x=offX + 500, y=offY + 0)

    # 第三行：输入框
    tk.Label(root, text="请输入高度", bg='green').place(x=offX + 350, y=offY + 35)
    entry_scale_width = StringVar()
    entry_path1 = Entry(root, textvariable=entry_scale_width)
    entry_path1.place(x=offX + 420, y=offY + 35)

    # 第四行：输入框
    tk.Label(root, text="请输入宽度", bg='green').place(x=offX + 350, y=offY + 65)
    entry_scale_height = StringVar()
    entry_path1 = Entry(root, textvariable=entry_scale_height)
    entry_path1.place(x=offX + 420, y=offY + 65)

    # 第三行：按钮
    button3 = Button(root, text="预览", command=lambda: preview_images(),
                     bg='skyblue')
    button3.place(x=offX + 350, y=offY + 95)

    button4 = tk.Button(root, text="切割当前", command=lambda: cur_plist_images())
    button4.place(x=offX + 525, y=offY + 95)

    button5 = Button(root, text="切割全部", command=lambda: plist_images())
    button5.place(x=offX + 600, y=offY + 95)
    tk.Label(root, text="勾选复选框生成txt", bg='green').place(x=offX+670, y=offY+65)
    tk.Checkbutton(root, variable=check_var).place(x=offX + 670, y=offY + 95)
    def btn_last_directory():
        global cur_directory_type_index, scale_index
        if cur_directory_type_index <= 0:
            messagebox.showerror("Error", "没有了")
            return
        cur_directory_type_index -= 1
        scale_index = 0

    def btn_next_directory():
        global cur_directory_type_index, scale_index
        if cur_directory_type_index >= len(imgs_Dic) - 1:
            messagebox.showerror("Error", "没有了")
            return
        cur_directory_type_index += 1
        scale_index = 0

    last_button = tk.Button(root, text="上一个", command=btn_last_directory)
    last_button.place(x=offX + 405, y=offY + 95)

    next_button = tk.Button(root, text="下一个", command=btn_next_directory)
    next_button.place(x=offX + 465, y=offY + 95)

    # 图像绘制位置坐标
    canvas = tk.Canvas(root, width=800, height=800, bg="gray")
    canvas.place(x=offX, y=offY + 130)

    def select_directory(entry):
        directory = filedialog.askdirectory(parent=root)
        entry.set(directory)
        root.lift()

    def select_out_directory(entry):
        directory = filedialog.askdirectory(parent=root)
        entry.set(directory)
        root.lift()

    def preview_images():
        global cur_directory_type_index
        cur_directory_type_index = 0
        plist_path = entry_scale_frame_path.get()
        png_frames_info = {}
        png_file_path = []
        png_info= {}
        png_full_path = ""

        sub_dir_path = ""
        index=0
        for sub_dir in os.listdir(plist_path):
            cur_frames_info= {}
            if sub_dir.endswith(".png"):
                png_full_path = os.path.join(plist_path, sub_dir)
                png_file_path.append(png_full_path)
                sub_dir_path = sub_dir
            if sub_dir.endswith(".plist"):
                # 读取 plist 文件
                plist_full_path = os.path.join(plist_path, sub_dir)
                with open(plist_full_path, 'rb') as fp:
                    plist_data = plistlib.load(fp)

                    frames_dict = plist_data.get('frames', {})

                    for png_name, frame_info in frames_dict.items():
                        # 将帧信息存储到字典中，以.png文件名作为键
                        cur_frames_info[png_name] = frame_info
                    png_info[index]=cur_frames_info
                    index+=1
        i = 0
        for png_path in png_file_path:
            cur_img = []
            image_atlas = Image.open(png_path)
            base_name = png_path
            dirName_Dic[i] = base_name
            for png_name, frame_info in png_info[i].items():
                print(f"Image: {png_name}")
                print(f"base_name: {png_name}")
                print(f"  Frame: {frame_info['frame']}")
                offset_x, offset_y = GetPList.getDicValue(frame_info['offset'])
                sourceSize_x, sourceSize_y = GetPList.getDicValue(frame_info['sourceSize'])
                frame_info_1_x, frame_info_1_y, sizeW, sizeH = GetPList.get_frame_info(frame_info['frame'])
                rotated_value = GetPList.get_rotated(frame_info['rotated'])
                width, height=getSize()
                if width or height > 0:
                    sourceSize_x = width
                    sourceSize_y = height
                back_image = Image.new("RGBA", (sourceSize_x, sourceSize_y))
                back_width,back_height=back_image.size
                # 旋转处理
                if rotated_value == True:
                    new_image = image_atlas.crop(
                        (frame_info_1_x, frame_info_1_y, frame_info_1_x + sizeH, frame_info_1_y + sizeW))
                    new_image = new_image.transpose(Image.ROTATE_90)
                else:
                    new_image = image_atlas.crop(
                        (frame_info_1_x, frame_info_1_y, frame_info_1_x + sizeW, frame_info_1_y + sizeH))
                back_image.paste(new_image, (int(back_width / 2) + offset_x - 24, int(back_height / 2) + offset_y - 18))
                cur_img.append(back_image)
            i += 1
            imgs_Dic[base_name] = cur_img
            print(imgs_Dic)
        update_frame_sclae()
    def getSize():
        width = int(entry_scale_width.get()) if entry_scale_width.get() else 0
        height = int(entry_scale_height.get()) if entry_scale_height.get() else 0
        return width,height
    def plist_images():

        GetPList.loadDire(entry_scale_frame_path.get(), entry_scale_out_path.get(),getSize()[0],getSize()[1],check_var.get())
    def cur_plist_images():
        GetPList.cur_loadDire(dirName_Dic[cur_directory_type_index],cur_directory_type_index,entry_scale_frame_path.get(), entry_scale_out_path.get(),getSize()[0],getSize()[1],check_var.get())
    # 预览
    def update_frame_sclae():
        global imgs_scale, scale_index, photo, resized_img, name, root_after2
        if cur_directory_type_index in dirName_Dic:
            canvas.delete("all")
            length = len(imgs_Dic[dirName_Dic[cur_directory_type_index]])
            img_scale = imgs_Dic[dirName_Dic[cur_directory_type_index]][scale_index]
            resize = [math.ceil(img_scale.size[0] * scale_value), math.ceil(img_scale.size[1] * scale_value)]
            resized_img = img_scale.resize(resize, Image.Resampling.LANCZOS)
            photo = ImageTk.PhotoImage(resized_img)
            x = int(photo.width() / 2)
            y = int(photo.height() / 2)

            canvas.create_rectangle(x - photo.width() / 2, y - photo.height() / 2, x + photo.width() / 2,
                                    y + photo.height() / 2, fill="white", outline="black")
            canvas.create_image(x, y, anchor=tk.CENTER, image=photo)

            scale_index = (scale_index + 1) % length  # 循环显示
        root_after2 = root.after(200, update_frame_sclae)
    if parent is None:
        root.mainloop()
if __name__ == "__main__":
    create_window()
